#include <time.h>
#include "LogThread.h"

LogThread::LogThread(void)
{
    m_currentLog = NULL;
    //单个log文件最大1000行
    setMaxLog(1000);
}

LogThread::~LogThread(void)
{
    if (NULL != m_currentLog)
    {
        fclose(m_currentLog);
    }
    m_currentLog = NULL;
}

void    LogThread::Run()
{
    while(true)
    {
        if (!m_messagePoll.isEmpty())
        {
            list<PRINTFTHREAD_ELEMENT_TYPE*>&    LocalList = m_messagePoll.makeCopyList();

            list<PRINTFTHREAD_ELEMENT_TYPE*>::iterator It = LocalList.begin();
            while(It != LocalList.end())
            {
                PRINTFTHREAD_ELEMENT_TYPE* tempSqlMessage = *It;
                if (NULL != tempSqlMessage)
                {
                    writeLogMessage(tempSqlMessage);
                    tempSqlMessage->init();
                    freeMessage(tempSqlMessage);
                }
                It = LocalList.erase(It);
            }
        }

        ThreadLib::YieldThread(1);
    }
}

void    LogThread::setMaxLog(int aMax)
{
    if (aMax > 0)
    {
        m_maxLog = aMax;
    }
}

void    LogThread::lock()
{
    m_mutex.lock();
}

void    LogThread::unLock()
{
    m_mutex.unLock();
}

void    LogThread::createLog()
{
    if (NULL != m_currentLog)
    {
        fclose(m_currentLog);
        m_currentLog = NULL;
    }

    if (NULL == m_currentLog)
    {
        char    timestr[1024];
        memset(timestr, '\0', sizeof(timestr));

        time_t    theTime;
        time(&theTime);
        tm&    t = *(localtime(&theTime));
        sprintf(timestr, "%d-%d-%d-%d-%d-%d.txt",t.tm_year+1900, t.tm_mon+1, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec);
        m_currentLog = fopen(timestr, "w");
    }

    m_printfCounter = 0;
}

void    LogThread::writeLogMessage(PRINTFTHREAD_ELEMENT_TYPE* pMsg)
{
    if (m_printfCounter >= m_maxLog || NULL == m_currentLog)
    {
        //如果还没有创建文件,或者文件已经过大,则重新建立文件
        createLog();
    }

    if (NULL != m_currentLog)
    {
        fputs(pMsg->getReadBuffer(), m_currentLog);
        fflush(m_currentLog);
        m_printfCounter ++;
    }
}

void    LogThread::pushLogMessage()
{
    PRINTFTHREAD_ELEMENT_TYPE*    message = getMessage();
    if (NULL != message)
    {
        message->writeBuffer((char*)(this->str().c_str()), this->str().length());
        message->writeValue<char>('\0');
        writeMessage(message);

    }
    this->str().clear();
}

ostream&    LogThread::endl(ostream& os)
{
    ostream* osptr = &os;
    LogThread* logptr = dynamic_cast<LogThread*>(osptr);
    if(NULL != logptr)
        logptr->pushLogMessage();
    return os;
}
